
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[EBAS_SP_GEM_FAG]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[EBAS_SP_GEM_FAG]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [DBO].[EBAS_SP_GEM_FAG] 
	@session varchar(255),
	@navn varchar(255),
	@karakterSkala varchar(255),
	@bogpakke varchar(255) = NULL
WITH ENCRYPTION
AS
	DECLARE @rettighed int,
		@antal int, 
		@guid uniqueidentifier,
		@karakterSkalaGuid uniqueidentifier,
		@bogpakkeGuid uniqueidentifier
	
	SET NOCOUNT ON
	SET @antal = 0
	SET @bogpakkeGuid = NULL

	CREATE TABLE #temp ( rett int )
	INSERT INTO #temp (rett)
	EXEC EBAS.DBO.EBAS_SP_SIKKERHED_VERIFICER_SESSION @session	

	SET @rettighed = (SELECT IsNull(MAX(rett),0) FROM #temp)
	
	IF 8 <= @rettighed 
	BEGIN
		SET @karakterSkalaGuid = ( SELECT GUID 
				 	   FROM EBAS_KARAKTER_SKALA
				 	   WHERE NAVN = @karakterSkala )
		
		IF @bogpakke IS NOT NULL
		BEGIN
			SET @bogpakkeGuid = ( 	SELECT GUID 
						FROM EBAS_BOGPAKKE
						WHERE NAVN = @bogpakke )
		END
		
		IF NOT EXISTS (SELECT 1 FROM EBAS_FAG WHERE NAVN = @navn)
		BEGIN
			SET @guid = newid()
			
			INSERT INTO EBAS_FAG
				SELECT 	@guid, @navn, @bogpakkeGuid, @karakterSkalaGuid 
		END
		ELSE
		BEGIN
			SET @guid = (SELECT GUID FROM EBAS_FAG WHERE NAVN = @navn)
			
			UPDATE 	EBAS_FAG
			SET 	NAVN = @navn, KARAKTER_SKALA_GUID = @karakterSkalaGuid,
				BOGPAKKE_GUID = @bogpakkeGuid
			WHERE	GUID = @guid
		END
	END

	SELECT 	F.GUID AS GUID, F.NAVN, F.BOGPAKKE_GUID, 
		F.KARAKTER_SKALA_GUID, S.NAVN AS KARAKTER_SKALA,
		0 AS ANTAL
	FROM 	EBAS_FAG F, EBAS_KARAKTER_SKALA S
	WHERE 	F.KARAKTER_SKALA_GUID = S.GUID
	AND 	F.GUID = @guid

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
